const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    newavatarUrl:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let userInfo = wx.getStorageSync('userInfo')
    let {_id,avatarUrl,account,nickName} = userInfo
    this.setData({
      _id:_id,
      avatarUrl:avatarUrl,
      account:account,
      nickName:nickName
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  /**
   *  更换用户头像
   */
  changeImage(){
    wx.chooseImage({
      count: 1,
    }).then(res=>{
      this.setData({
        avatarUrl:res.tempFilePaths[0],
        newavatarUrl:res.tempFilePaths[0]
      })
    }).catch(()=>{
      wx.showToast({
        title: '取消上传',
        icon:'none'
      })
    })
  },

  /**
   * 保存修改
   */
  async formSubmit(e){
    let avatarUrl = this.data.newavatarUrl
    let _id = this.data._id
    let {nickName,account} = e.detail.value
    if(nickName.length == 0 ){
      nickName = this.data.nickName
    }
    if(account.length == 0 ){
      account = this.data.account
    }
    await this.uploaduserInfo(avatarUrl,nickName,account,_id)
    
  },

  /**
   * 上传用户信息到云端
   */
  uploaduserInfo(avatarUrl,nickName,account,_id){
    console.log(avatarUrl.length)
    if(avatarUrl.length != 0 ){
      wx.cloud.uploadFile({
        cloudPath:'userPic/'+Date.now()+'.png',
        filePath:avatarUrl,
      }).then(res=>{
        let fileId = res.fileID
        db.collection('userList').doc(_id).update({
          data:{
            account:account,
            nickName:nickName,
            avatarUrl:fileId
          },
        }).then(()=>{
          console.log('上传成功')
          db.collection('userList').doc(_id).get().then(value=>{
            wx.setStorageSync('userInfo',value.data)
            wx.reLaunch({
              url: '/pages/mine/mine',
            })
          }).catch(error=>{
            console.log('查询失败')
          })
        })
      })
    }else{
      db.collection('userList').doc(_id).update({
        data:{
          account:account,
          nickName:nickName,
        },
      }).then(()=>{
        console.log('上传成功')
        db.collection('userList').doc(_id).get().then(value=>{
          wx.setStorageSync('userInfo',value.data)
          wx.reLaunch({
            url: '/pages/mine/mine',
          })
        }).catch(error=>{
          console.log('查询失败')
        })
      })
    }
  }
})